﻿using AutoMapper;
using JTTD.DataBase;
using JTTD.Domain.Dtos;
using JTTD.Domain.Dtos.ShopCoupon.Request;
using JTTD.Domain.Dtos.ShopCoupon.Response;
using JTTD.Domain.IService;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JTTD.Domain.Service
{
    /// <summary>
    /// 店铺优惠券服务
    /// </summary>
    public class ShopCouponService : IShopCouponService
    {
        private readonly JTTDContext _dbContext;
        private readonly IMapper _mapper;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="mapper"></param>
        public ShopCouponService(JTTDContext dbContext, IMapper mapper)
        {
            _dbContext = dbContext;
            _mapper = mapper;
        }
        /// <summary>
        /// 核销店铺优惠券
        /// </summary>
        /// <param name="no"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> ChangeShopCoupon(string no)
        {
            try
            {
                var coupon = await _dbContext.ShopCouponInfoModels.FirstOrDefaultAsync(item => item.ShopCouponNumber == no.Trim());
                if (coupon == null)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "没有找到指定优惠券" };
                }
                coupon.IsUse = true;
                _dbContext.ShopCouponInfoModels.Update(coupon);
                await _dbContext.SaveChangesAsync();
                return new ApiResult<bool> { IsSuccess=true,Message="操作成功"};
            }
            catch( Exception ex)
            {
                return new ApiResult<bool> { IsSuccess=false,Message="操作失败，"+ex.Message};
            }
           
        }

        /// <summary>
        /// 分页获取用户可使用的店铺优惠券
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult<PageResult<ShopCouponResponseDto>>> GetShopCouponPageList(int userId,ShopCouponSearchRequestDto dto)
        {
            var query = _dbContext.ShopCouponInfoModels.Where(item=>item.UserId==userId&&!item.IsUse);
            if(dto.Type.HasValue)
            {
                query = query.Where(item=>item.Type==dto.Type.Value);
            }
            if(!string.IsNullOrWhiteSpace(dto.ShopName))
            {
                var shop=await  _dbContext.CompanyUserInfoModels.FirstOrDefaultAsync(item=>item.UserName.Contains(dto.ShopName));
                if (shop==null)
                {
                    return new ApiResult<PageResult<ShopCouponResponseDto>>
                    {
                        IsSuccess=true,Message="没有找到符合条件的店铺优惠券",Data=new PageResult<ShopCouponResponseDto>
                        {
                            Data =new List<ShopCouponResponseDto>(),
                            PageIndex =dto.PageIndex ,PageSize=dto.PageSize
                        }
                    };
                }
                query = query.Where(item => item.ShopId == shop.Id);
            }
            int count = await query.CountAsync();
            if (count>0)
            {
                var list = await query.OrderBy(item => item.EndTime).ThenByDescending(item=>item.CouponAmount).Skip((dto.PageIndex - 1) * dto.PageSize).Take(dto.PageSize).ToListAsync();
                var tempList = _mapper.Map<List<ShopCouponResponseDto>>(list);
                var shopIds = list.Select(item => item.ShopId).Distinct().ToList();
                var shopList=await  _dbContext.CompanyUserInfoModels.Where(item => shopIds.Contains(item.Id)).ToListAsync();
                foreach (var item in tempList)
                {
                    item.ShopName = shopList.FirstOrDefault(args => args.Id == item.ShopId)?.UserName;
                }
                return new ApiResult<PageResult<ShopCouponResponseDto>>()
                {
                    Data = new PageResult<ShopCouponResponseDto>()
                    {
                        Data = tempList,
                        PageIndex = dto.PageIndex,
                        PageSize = dto.PageSize,
                        TotalNum = count,
                        TotalPageNum = (count % dto.PageSize) == 0 ? count / dto.PageSize : count / dto.PageSize + 1
                    },
                    IsSuccess = true

                };
            }
            else
            {
                return new ApiResult<PageResult<ShopCouponResponseDto>>
                {
                    IsSuccess = true,
                    Message = "没有找到符合条件的店铺优惠券",
                    Data = new PageResult<ShopCouponResponseDto>
                    {
                        Data = new List<ShopCouponResponseDto>(),
                        PageIndex = dto.PageIndex,
                        PageSize = dto.PageSize
                    }
                };
            }
        }

        /// <summary>
        /// 分页获取用户领取当前店铺的所有店铺优惠券
        /// </summary>
        /// <param name="shopId"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async  Task<ApiResult<PageResult<ShopCouponResponseDto>>> GetShopCouponPageListByShop(int shopId, ShopCouponSearchByShopRequestDto dto)
        {
            var query = _dbContext.ShopCouponInfoModels.Where(item => item.ShopId == shopId);
            if (dto.Type.HasValue)
            {
                query = query.Where(item => item.Type == dto.Type.Value);
            }
            if (!string.IsNullOrWhiteSpace(dto.ShopCouponNumber))
            {
               
                query = query.Where(item => item.ShopCouponNumber == dto.ShopCouponNumber);
            }
            if (!string.IsNullOrWhiteSpace(dto.Phone))
            {
                var user = await _dbContext.UserInfos.FirstOrDefaultAsync(item=>item.Phone==dto.Phone.Trim());
                if(user==null)
                {
                    return new ApiResult<PageResult<ShopCouponResponseDto>>
                    {
                        IsSuccess = true,
                        Message = "没有找到符合条件的店铺优惠券",
                        Data = new PageResult<ShopCouponResponseDto>
                        {
                            Data = new List<ShopCouponResponseDto>(),
                            PageIndex = dto.PageIndex,
                            PageSize = dto.PageSize
                        }
                    };
                }
                query = query.Where(item=>item.UserId==user.Id);
            }
            int count = await query.CountAsync();
            if (count > 0)
            {
                var list = await query.OrderByDescending(item => item.CreateTime).Skip((dto.PageIndex - 1) * dto.PageSize).Take(dto.PageSize).ToListAsync();
                var tempList = _mapper.Map<List<ShopCouponResponseDto>>(list);
                var userIds = list.Select(item => item.UserId).Distinct().ToList();
                var userList = await _dbContext.UserInfos.Where(item => userIds.Contains(item.Id)).ToListAsync();
                foreach (var item in tempList)
                {
                    item.UserNumber = userList.FirstOrDefault(args => args.Id == item.UserId)?.UserNumber;
                }
                return new ApiResult<PageResult<ShopCouponResponseDto>>()
                {
                    Data = new PageResult<ShopCouponResponseDto>()
                    {
                        Data = tempList,
                        PageIndex = dto.PageIndex,
                        PageSize = dto.PageSize,
                        TotalNum = count,
                        TotalPageNum = (count % dto.PageSize) == 0 ? count / dto.PageSize : count / dto.PageSize + 1
                    },
                    IsSuccess = true

                };
            }
            else
            {
                return new ApiResult<PageResult<ShopCouponResponseDto>>
                {
                    IsSuccess = true,
                    Message = "没有找到符合条件的店铺优惠券",
                    Data = new PageResult<ShopCouponResponseDto>
                    {
                        Data = new List<ShopCouponResponseDto>(),
                        PageIndex = dto.PageIndex,
                        PageSize = dto.PageSize
                    }
                };
            }
        }

    }
}
